
package com.cmc.dao.hibernate;

import java.util.List;

import com.cmc.dao.hibernate.BaseDaoHibernate;
import com.cmc.model.Nation;
import com.cmc.dao.NationDao;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.criterion.Example;
import org.hibernate.criterion.MatchMode;
import org.springframework.orm.ObjectRetrievalFailureException;
import org.springframework.orm.hibernate3.HibernateCallback;

public class NationDaoHibernate extends BaseDaoHibernate implements NationDao {

    /**
     * @see com.cmc.dao.NationDao#getNations(com.cmc.model.Nation)
     */
    public List getNations(final Nation nation) {
        //return getHibernateTemplate().find("from Nation");

        /* Remove the line above and uncomment this code block if you want 
           to use Hibernate's Query by Example API.*/
        if (nation == null) {
            return getHibernateTemplate().find("from Nation");
        } else {
            // filter on properties set in the nation
            HibernateCallback callback = new HibernateCallback() {
                public Object doInHibernate(Session session) throws HibernateException {
                    Example ex = Example.create(nation).ignoreCase().enableLike(MatchMode.ANYWHERE);
                    return session.createCriteria(Nation.class).add(ex).list();
                }
            };
            return (List) getHibernateTemplate().execute(callback);
        }
    }

    /**
     * @see com.cmc.dao.NationDao#getNation(Long id)
     */
    public Nation getNation(final Long id) {
        Nation nation = (Nation) getHibernateTemplate().get(Nation.class, id);
        if (nation == null) {
            log.warn("uh oh, nation with id '" + id + "' not found...");
            throw new ObjectRetrievalFailureException(Nation.class, id);
        }

        return nation;
    }

    /**
     * @see com.cmc.dao.NationDao#saveNation(Nation nation)
     */    
    public void saveNation(final Nation nation) {
        getHibernateTemplate().saveOrUpdate(nation);
    }

    /**
     * @see com.cmc.dao.NationDao#removeNation(Long id)
     */
    public void removeNation(final Long id) {
        getHibernateTemplate().delete(getNation(id));
    }
}
